import React, { useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../store";
import { useNavigate } from "react-router-dom";
import { Button } from "react-vant";
import axios from "axios";

const Index: React.FC = () => {
  const token = useSelector((state: RootState) => state.user.token);
  const nickname = useSelector((state: RootState) => state.user.nickname);
  const avator = useSelector((state: RootState) => state.user.avator);
  const navigate = useNavigate();
  const input = useRef<HTMLInputElement | null>(null);
  const dispatch = useDispatch()
  const handleClick = () => {
    input.current?.click();
  };
  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const input = e.target;
    const files = input.files
    const file = files![0]

    const formData = new FormData();
    formData.append('file', file, file.name)

    const resp = await axios.post('/api/upload', formData)
    console.log(resp.data.data.url)
    dispatch({ type: 'setAvator', payload: resp.data.data.url })
  };
  return (
    <div>
      <input
        ref={input}
        type="file"
        style={{ display: "none" }}
        onChange={(e) => handleChange(e)}
      />
      {token ? (
        <div
          style={{
            display: "flex",
            justifyContent: "space-around",
            alignItems: "center",
            height: 150,
            borderBottom: "1px solid #ccc",
          }}
        >
          <span>{nickname}</span>
          <img
            src={avator}
            alt=""
            width={100}
            height={100}
            style={{ borderRadius: "50%" }}
            onClick={() => handleClick()}
          />
        </div>
      ) : (
        <div
          style={{
            display: "flex",
            justifyContent: "space-around",
            alignItems: "center",
            height: 150,
            borderBottom: "1px solid #ccc",
          }}
        >
          <Button type="primary" onClick={() => navigate("/login")}>
            还未登录，去登录吧
          </Button>
        </div>
      )}
    </div>
  );
};

export default Index;
